package cn.wgx.common.config;

import cn.wgx.common.util.SwaggerUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 公共配置
 */
@Configuration
@EnableFeignClients
@EnableSwagger2
@ConfigurationProperties("swagger")
public class CommonConfig {

    public List<String> basePackage = new ArrayList<String>(){{add("cn.wgx");}};

    //通过配置添加swagger需要扫描的包
    private List<String> otherpackage = new ArrayList<>();

    /**
     * swagger 扫描全包接口
     * @return
     */
    @Bean
    public Docket allApi() {
        basePackage.addAll(otherpackage);
        return SwaggerUtil.createDocket(basePackage , SwaggerUtil.API_TITLE, SwaggerUtil.DESCRIPTION);
    }


    //http客户端,可以发送http请求
    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().addAll(getConverts());
        return restTemplate;
    }



    private List<HttpMessageConverter<?>> getConverts() {
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        // String转换器
        StringHttpMessageConverter stringConvert = new StringHttpMessageConverter();
        List<MediaType> stringMediaTypes = new ArrayList<MediaType>() {{
            //添加响应数据格式，不匹配会报401
            add(MediaType.TEXT_PLAIN);
            add(MediaType.TEXT_HTML);
            add(MediaType.APPLICATION_JSON);
        }};
        stringConvert.setSupportedMediaTypes(stringMediaTypes);
        messageConverters.add(stringConvert);
        return messageConverters;
    }

}
